package handlers

import (
	"chatroom/shared"
	"encoding/json"
	"fmt"
	"sync"

	amqp "github.com/rabbitmq/amqp091-go"
)

type ClientInfo struct {
	ClientName string  `json:"client_name"`
	ClientID   string  `json:"client_id"`
	TimeStamp  float64 `json:"time_stamp"`
}

var onlineClients map[string]ClientInfo = make(map[string]ClientInfo, 10)

var mutex sync.Mutex

type HeartbeatHandler struct {
	onlineClients map[string]string
	ch            *amqp.Channel
}

func (h *HeartbeatHandler) Handle(cmd string) error {
	mutex.Lock()
	defer mutex.Unlock()
	var clientInfo ClientInfo
	err := json.Unmarshal([]byte(cmd), &clientInfo)
	if err != nil {
		return err
	}

	_, ok := onlineClients[clientInfo.ClientID]
	onlineClients[clientInfo.ClientID] = clientInfo
	if !ok {
		msg := fmt.Sprintf("Register successfully, Total online clients: %d", len(onlineClients))
		cmd := shared.CommandMsg{
			Command: "heartbeatresp",
			Body:    msg,
		}
		cmdJson, err := json.Marshal(cmd)
		if err != nil {
			return err
		}
		err = h.ch.Publish(
			"",
			clientInfo.ClientID,
			false,
			false,
			amqp.Publishing{
				Body: []byte(cmdJson),
			},
		)
		if err != nil {
			return err
		}
	}
	return nil
}
